import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"

Vue.use(VueRouter)

const routes = []
// webpack的api用来会历文件夹中的指定文件实现自动导入:require.context()
const file = require.context('./routes', false, /\.js$/i)
file.keys().forEach(item => {
  // file(item).default就是每个路由文件的内容
  let ret = file(item).default
  Array.isArray(ret) ? routes.push(...ret) : routes.push(ret)
})

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  // 挂载
  routes
})

router.beforeEach((to, from, next) => {
  // console.log(store.getters.token);
  if (to.path != "/login") {
    if (store.getters.token == "") {
      next({ path: '/login', replace: true })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router

